package 二叉树.叶子节点个数;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/31 11:22
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1,new TreeNode(2),new TreeNode(3,new TreeNode(4),null));
        System.out.println(fun(root));
    }

    //先序遍历
    public static int singleNodeNum(TreeNode root){
        int num1 ,num2,n;
        if (root == null){
            return 0;
        }else if (root.left == null && root.right == null){
            n = 1;
        }else {
            n = 0;
        }
        num1 = singleNodeNum(root.left);
        num2 = singleNodeNum(root.right);
        return n+num1+num2;
    }

    //层次遍历
    public static int fun(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int res = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left == null && node.right == null) {
                    res++;
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                size--;
            }
        }
        return res;
    }
}
